import axios, { AxiosInstance, AxiosRequestConfig } from 'axios'
class HttpRequest {
  private readonly baseUrl: string
  constructor() {
    this.baseUrl = `http://localhost:3000`
  }
  getInsideConfig() {
    const config = {
      baseUrl: this.baseUrl, // 请求前缀
      timeout: 6000, // 请求超时
      withCredentials: true // 异步请求携带cookie
      // headers: {
      // 设置后端需要的传参类型
      // 'Content-Type': 'application/json',
      // 'token': x-auth-token',//一开始就要token
      // 'X-Requested-With': 'XMLHttpRequest',
      // },
    }
    return config
  }
  //请求拦截
  interceptors(instance: AxiosInstance, url: string | number | underfined) {
    // 请求拦截器
    instance.interceptors.request.use(
      config => {
        // 1. 添加全局的Loading
        // 2. 请求头携带token
        return config
      },
      (error: any) => {
        return Promise.reject(error)
      }
    )
    //响应拦截
    instance.interceptors.response.use(
      res => {
        const { data } = res
        console.log('返回数据处理', res)
        return data
      },
      (error: any) => {
        switch (error.response.status) {
          case 400:
            console.log('请求错误')
            break
          case 401:
            console.log('未授权,请重新登录')
            break
          case 403:
            console.log('拒绝访问')
            break
          case 404:
            console.log('请求出错')
            break
          case 408:
            console.log('请求超时')
            break
          case 500:
            console.log('服务器错误')
            break
          case 502:
            console.log('网络错误')
            break
          case 503:
            console.log('服务不可用')
            break
          case 504:
            console.log('网络超时')
            break
          case 505:
            console.log('HTTP版本不支持')
            break
          default:
            console.log(`连接出错(${error.response.status})!`)
        }
        console.log('error==>', error)
        return Promise.reject(error)
      }
    )
  }
  request(options: AxiosRequestConfig) {
    const instance = axios.create()
    options = Object.assign(this.getInsideConfig(), options)
    this.interceptors(instance, options.url)
    return instance(options)
  }
}
const http = new HttpRequest()
export default http
